package com.bawei.goods.hospital_goods.es.EsService;


import com.alibaba.fastjson.JSON;
import com.bawei.common.config.GuliESConfig;
import com.bawei.goods.hospital_goods.entity.GoodTableEntity;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
public class EsServiceImpl implements EsTService {

    @Autowired
    private RestHighLevelClient client;


    @Override
    public void upOrDownGood(String status, GoodTableEntity byId) {

        if (status.equals("1")){
            esUp(byId);
        }else {
            System.out.println(byId.getId());
            DeleteRequest request = new DeleteRequest(
                    "medicagroup",
                    byId.getId()+"");
            try {
                DeleteResponse deleteResponse = client.delete(
                        request, GuliESConfig.COMMON_OPTIONS);

                System.out.println("返回结果"+deleteResponse.status());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    private void esUp(GoodTableEntity byId) {
        IndexRequest request = new IndexRequest("medicagroup");
        request.id(byId.getId()+"");
        String jsonString = JSON.toJSONString(byId);
        request.source(jsonString,XContentType.JSON);
        try {
            IndexResponse indexResponse = client.index(request, GuliESConfig.COMMON_OPTIONS);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
